/**
 * winchance Inc.
 * Copyright (c) 2010-2014 All Rights Reserved.
 */
package com.gm.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 不可逆加密(摘要)
 * @author 卡内齐 (kaneiqi@dajiaok.com)
 * @version $Id: Md5Utils.java, v 0.1 2014-6-4 下午01:06:54 kaneiqi Exp $
 */
public class Md5Utils {

    private static final Log logger = LogFactory.getLog(Md5Utils.class);

    /**
     * 32位MD5摘要不可逆算法
     * @return 
     */
    public static String encrypMD5_32(String password) {
        return Md5(password, 32);
    }

    /**
     * 16位MD5摘要不可逆算法
     * @return 
     */
    public static String encrypMD5_16(String password) {
        return Md5(password, 16);
    }

    /**
     * MD5 计算 加密 
     * @param plainText
     * @return
     */
    private static String Md5(String plainText, int bit) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            // 32位加密
            if (32 == bit) {
                return buf.toString();
            }
            // 16位加密
            if (16 == bit) {
                return buf.toString().substring(8, 24);
            }

        } catch (NoSuchAlgorithmException e) {
            logger.error("md5加密异常", e);
        }
        return null;
    }
}
